<!DOCTYPE html>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>管理者页面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta content="width=device-width, initial-scale=1" name="viewport">
<link rel="stylesheet" type="text/css" href="${contextPath}/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="${contextPath}/css/bootstrap-theme.min.css" />
<link rel="stylesheet" type="text/css" href="${contextPath}/css/public.css">
<script type="text/javascript" src="${contextPath}/js/jquery.min.js"></script>
<script type="text/javascript" src="${contextPath}/js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="${contextPath}/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="${contextPath}/js/bootstrap.min.js"></script>
<script type="text/javascript" src="${contextPath}/js/common.js"></script>
<style type="text/css">
.my_img{
	height: 180px;
	width: 320px;
}
</style>
</head>
<body>
	<div class="container">
		<div class="panel panel-default">
			<div class="panel-heading">待审核任务信息<span id="taskUlT" class="pull-right text-success"></span></div>
			<div class="panel-body">
				<button type="button" id="downTask" class="btn btn-warning">下载待审核任务</button>
				<button type="button" id="qualifiedBtn" class="btn btn-success">审核合格</button>
			<!--	<button type="button" id="unqualifiedBtn" class="btn btn-danger">审核不合格</button>
			 	<select class="btn btn-primary" id="sendBackType">
					<option value="1">单个退回</option>
					<option value="2">批量退回</option>
				</select> -->
				<div style="float: right;">
					<form action="${contextPath}/security/inpsUpTagAndTextGrid" method="post" name="inpsUpTagAndTextGrid" role="form" class="form-inline" enctype="multipart/form-data">
					<label for="TAG" class="control-label">选择要修改的任务</label> &nbsp;&nbsp;
					<input type="file" style="width: 75px; height: 20px; display: inline-block;" name="file" id="fileupload" autocomplete="off" multiple/>&nbsp;&nbsp;
					<span class="help-block" style="display: inline-block;" id="uploadHelp">已选择0个文件</span>&nbsp;&nbsp;
					<button id="uploadBtn" type="button" class="btn btn-primary">上传文件</button>
					</form>
				</div>
			</div>
			<table class="table table-striped table-bordered">
				<thead>
					<tr>
						<th width='6%'>序号</th>
						<th width='10%'>工作者</th>
						<th width='20%'>任务名称</th>
						<th width='20%'>上传时间</th>
						<th width='18%'>标注时间</th>
						<th width='15%'>最后修改用户</th>
						<th width='6%'>操作</th>
					</tr>
				</thead>
				<tbody></tbody>
			</table>
		</div>
	</div>
	<!-------------------------------- 弹出窗口 -------------------------------------------------->
	<div id="unqualifiedModal" class="modal fade">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
					<h4 class="modal-title">审核不合格</h4>
				</div>
				<div class="modal-body">
					<form class="form" role="form">
						<div class="form-group" id="reTime">
							<div class="input-group">
								<span class="input-group-addon">修改回传时间：</span>
								<input class="form-control" onkeydown="if(event.keyCode==13){return false;}" id="day" type="number" min="0" placeholder="填入数字，修改回传时间">
								<span class="input-group-addon">小时</span>
							</div>
						</div>
						<div class="form-group" id="errorTypes">
							<c:forEach items="${errorTypeList }" var="p">
								<input  style="cursor: pointer;" id="errorType_${p.id }" type="checkbox" value="${p.id }" onclick="addText(this.id,'${p.paramName }');"/><span  style="cursor: pointer;" onclick="chooseCheckBox('${p.id }')">${p.paramName }</span>&nbsp;&nbsp;&nbsp;&nbsp;
							</c:forEach>
						</div>
						<div class="form-group" id="">
							 <label class="control-label" for="unqualifiedReason">添加不合格原因</label>
							<textarea id="unqualifiedReason" class="form-control" rows="3" maxlength="200"></textarea>
						</div>
						<input type="hidden" id="unqualifiedImgName"/>
					</form>
					<span id="sendBackTypeMsg" style="color:red;"></span>
					<br/>
					<span>请在下方粘贴您要上传的截图:</span>
					<div id = "tar_box" contenteditable style="width: 320px;height: 180px; border:1px solid"> 
					</div> 
				</div>
				<div class="modal-footer">
					<button type="button" id="unpualifiedSubmitBtn" class="btn btn-primary">提交</button>
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
				</div>
			</div><!-- /.modal-content -->
		</div><!-- /.modal-dialog -->
	</div><!-- /.modal -->
	<script type="text/javascript">
		var packId = '${packId}';
		var percent = '${percent}';
		var packName = '${packName}';
		var taskList = "";
		var firstDate = "";
		var lastDate = "";
		var sendBackType;
		var unqualifiedImgName;
		$(document).ready(function(){
			loadTaskList();
			$("#statu").change(function(){
				$this = $(this);
				$this.val() == "0"?$("#reTime").show():$("#reTime").hide();
			});
			/*--------------------------------------下载待审核任务-------------------------------------------------------*/
			$("#downTask").click(function(){
				if(taskList.size == 0){
					alert("暂无待审核任务！");
				}else{
					$.ajax({
						type:'POST',
						data:{"list":taskList,"packName":packName},
						url:'${contextPath}/security/downAuditTaskForInspectByPackage',
						dataType:'json',
						success:function(data){
							if(data.wrongPath != ""){
								window.open("${contextPath}"+data.wrongPath);
							}
						}
					});
				}
			});
			/*--------------------------------------审核任务-------------------------------------------------------*/
			
			$("#qualifiedBtn").click(function(){//成功
				var conWin = confirm("确定该任务审核合格吗？");
				if(conWin){
					var day = 0;
					var taskEffective = 1;
					sendBackType = 0;  //审核合格时 设置为0
					postQualifyFn(taskEffective,day,"");
				}
			});
			var workerIdsUnique = [];
			var unqualifiedTaskIds = [];
			$("#unqualifiedBtn").click(function(){
				workerIdsUnique = [];
				var checkedNum = $(".unqualifiedCheckbox:checked").length;//已经选择的不合格任务数 
				if(checkedNum==0){  //不选择时则点击不合格按钮提示选择 什么都不执行
					alert("请选择不合格的任务~!");
				}else{
					//删除之前上传的截图
					if($("#tar_box").children().length>=1){
						$("#tar_box").children().remove();
						$("#unqualifiedImgName").val("");
					}
					/*--------------去除已经选择的checkbox中的重复userId---开始------*/
					var checkedworkerIds = []; 
					for(var i = 0; i<checkedNum; i++){
						checkedworkerIds.push($(".unqualifiedCheckbox:checked").eq(i).val());
					}
					var hash = {};
					for (var i = 0, elem; (elem = checkedworkerIds[i]) != null; i++) {
						if (!hash[elem]) {
							workerIdsUnique.push(elem);
							hash[elem] = true;
						}
					}
			//		alert(workerIdsUnique);
					/*--------------去除已经选择的checkbox中的重复userId---结束------*/
					/*--------------任务退回类型处理---开始------*/	
					sendBackType = $("#sendBackType").val();
					if(sendBackType==1){
						$("#sendBackTypeMsg").html("已选择单个任务退回~!");
						$("#tar_box").show();			
					}else{
						$("#sendBackTypeMsg").html("已选择批量任务退回~!");			
						$("#tar_box").hide();
					}
					unqualifiedTaskIds = [];
					$(".unqualifiedCheckbox:checked + .unqualifiedTaskId").each(function(){
						unqualifiedTaskIds.push($(this).val());
					});
					/*--------------任务退回类型处理---结束------*/	
					$("#unqualifiedModal").modal('show');
				}
			});
			$("#unpualifiedSubmitBtn").click(function(){
				var day = $("#day").val();
				if(day == "")day = 0;
				if(day == 0){
					$("#day").parent(".input-group").addClass("has-error").focus();
					return;
				}else{
					$(".has-error").removeClass("has-error");
					var resaon = $("#unqualifiedReason").val();
					if(resaon == ""){
						var comW = confirm("确定不填写不合格原因吗？");
						if(comW){
							resaon = "";
						}else{
							return;
						}
					}
					postQualifyFn(0,day,resaon);
					$("#unqualifiedModal").modal('hide');
				}
			});
			postQualifyFn = function(taskEffective,day,note){
				if(taskEffective!=0){   //审核合格或不合格时处理一些参数
					workerIdsUnique=[];
				}else{
					if(sendBackType==1){
						unqualifiedImgName = $("#unqualifiedImgName").val();
					}else{
						unqualifiedImgName = "";
					}
				}
			
				$.ajax({
					type:'POST',
					data:{"taskEffective":taskEffective,"day":day,"note":note,"packId":packId,"unqualifiedWorkerIds":workerIdsUnique,"sendBackType":sendBackType,"unqualifiedTaskIds":unqualifiedTaskIds,"imgName":unqualifiedImgName},
					url:'${contextPath}/security/auditingForInspectByPackage',
					dataType:'json',
					traditional:true,
					success:function(data){
						if($(".alert").length>0)$(".alert").remove();
						var $alertMsg = $("<div class='alert alert-dismissable'>"+data.message+"</div>");
						$alertMsg.append("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>");
						if(data.replay == "1"){
							$alertMsg.addClass("alert-success");
						}else{
							$alertMsg.addClass("alert-danger");
						}
						$(".panel-body").prepend($alertMsg);
						//loadTaskList(); //刷新页面会重新抽取随机数据  导致审核下载的和列表中的数据对应不上 
						
						if(taskEffective==1){
							loadTaskList();  // 审核合格时刷新页面
						}else{  //审核不合格不重新向服务器请求刷新页面    将不合格的从列表中删除
							var sendBackTaskIds = data.sendBackTaskIds;
							for ( var i = 0; i < sendBackTaskIds.length; i++) {
								if(sendBackType=="1"){
									$(".unqualifiedTaskId[value="+sendBackTaskIds[i]+"]").prev().attr("checked",false).attr("disabled","disabled");
									$("#tr_"+sendBackTaskIds[i]).remove();
								}else{
									var sendBackWorkerId = $(".unqualifiedTaskId[value="+sendBackTaskIds[i]+"]").prev().val();
									$(".unqualifiedCheckbox[value="+sendBackWorkerId+"]").attr("checked",false).attr("disabled","disabled");
									$(".unqualifiedCheckbox:disabled + .unqualifiedTaskId").each(function(){
										$("#tr_"+$(this).val()).remove();
									});
								}
							}
							if($("tbody tr").length==0){
								$("#downTask").attr("disabled","disabled");
								$("#qualifiedBtn").attr("disabled","disabled");
								$("#unqualifiedBtn").attr("disabled","disabled");
								$("#sendBackType").attr("disabled","disabled");
								$("tbody").empty();
								$("tbody").append("<tr class='text-danger'><td colspan='7'>无内容</td></tr>");
							}
						}
					}
				});
			};
			
		});
		/*--------------------------------------加载列表-------------------------------------------------------*/
		loadTaskList = function(){
			$.ajax({
				type:'POST',
				data:{"packId":packId,"percent":percent},
				url:'${contextPath}/security/inspectorByPackageList',
				dataType:'json',
				success:function(data){
					$("tbody").empty();
					if(data.list == ""){
						$("#downTask").attr("disabled","disabled");
						$("#qualifiedBtn").attr("disabled","disabled");
						$("#unqualifiedBtn").attr("disabled","disabled");
						$("#sendBackType").attr("disabled","disabled");
						$("tbody").empty();
						$("tbody").append("<tr class='text-danger'><td colspan='7'>无内容</td></tr>");
					}else{
						
						firstDate = data.firstDate;
						lastDate = data.lastDate;
						$("#taskUlT").text("最早上传时间："+firstDate+"最后上传时间："+data.lastDate);
						$.each(data.list,function(i,item){
							if(i == 0){
								taskList = item.taskId;
							}else{
								taskList +="_"+item.taskId;
							}
							
							$("tbody").append(
								"<tr id='tr_"+item.taskId+"'>"+
									"<td>"+(i+1)+"</td>"+
									"<td>"+item.workerRealName+"</td>"+
									"<td>"+item.taskName+"</td>"+
									"<td>"+item.taskUploadTime+"</td>"+
									"<td>"+item.taskMarkTime+"</td>"+
									"<td>"+item.taskStatu+"</td>"+
									"<td><input class='unqualifiedCheckbox' type='checkbox' value='"+item.workerId+"'/><input class='unqualifiedTaskId' type='hidden' value='"+item.taskId+"'/></td>"+
								"</tr>"
							);
						});
					}
				}
			});
		};
		function addText(id,errorTypeText){
			if($("#"+id).get(0).checked){
				var text = $("#unqualifiedReason").val();
				text = text + errorTypeText;
				text = text + "  ";
				$("#unqualifiedReason").val(text);
			}else{
				var text = $("#unqualifiedReason").val();
				text = text.replace(errorTypeText,'');
				$("#unqualifiedReason").val(text);
			}	
		}
		function chooseCheckBox(tempId){
			var id = "#errorType_"+tempId;
			$(id).trigger("click");
		}
		/*******************************多文件上传**************************************************/
			var modifyTaskIds=[];
			$("#fileupload").click(function(){
				modifyTaskIds=[];
				$(".unqualifiedTaskId").each(function(i){
					modifyTaskIds.push($(this).val());
				});
				
			});
			$("#fileupload").fileupload({
				singleFileUploads : false,
				formAcceptCharset : 'gb2312',
				typ : "POST",
				dataType : "json",
				url : "${contextPath}/security/inpsUpTagAndTextGrid",
				add : function(e, data) {
					var $this = $(this);
					data.autoUpload = false;
					var fileNum = data.files.length;
					//-------------验证开始
					var reg = /(\.|\/)(textgrid)$/i;
					for(var i = 0; i<fileNum;i++){
						if(!(reg.test(data.files[i].name))){//文件格式验证
							alert("选择文件含有格式不正确文件,请重新选择!");
							return false;
						}
					}
					//-------------验证结束
					$("#uploadHelp").text("已选择" + fileNum+ "个文件");
					$("#uploadBtn").click(function() {
						if (data.files.length == 0) {
							$("#uploadHelp").text("请选择上传的文件");
							return false;
						};
						data.submit();
						$(this).attr("disabled","disabled").text("上传中。。");
	
					});
				},
				done : function(e, result) {
					if(result.result.msg=="1"){
						alert("文件修改成功!修改了"+result.result.returnList.length+"个文件! 修改过的文件将被标注红色背景!");
						$("#uploadBtn").removeAttr("disabled").text("上传文件");
						$("#uploadBtn").unbind("click");
						$("#uploadHelp").text("已选择0个文件");
					}else if(result.result.msg=="2"){
						alert("文件修改出错,请联系系统维护人员!");
						$("#uploadBtn").text("上传文件");
					}else if(result.result.msg=="3"){
						alert("没有文件被更改,如有问题请联系系统维护人员!");
						$("#uploadBtn").removeAttr("disabled").text("上传文件");
						$("#uploadBtn").unbind("click");
						$("#uploadHelp").text("已选择0个文件");
					}
					
					for(var i = 0; i<result.result.returnList.length;i++){
						$("#tr_"+result.result.returnList[i]).find("td").each(function(){
							$(this).css("background-color","red");
						});
					}
					
				}
			});
			 //文件上传前触发事件
		    $("#fileupload").bind("fileuploadsubmit", function (e, data) {
		        data.formData = { "taskIds": modifyTaskIds };  
		    });
		    
/************************ctrl+v 图片上传*****************************************/
document.getElementById("tar_box").addEventListener('paste', function (event) {
//	console.log(event);
	if($("#tar_box").children().length>=1){
		var flag = window.confirm("已上传过截图,是要覆盖之前的截图吗?");
		if(!flag ){
			return false;
		}
		$("#tar_box").children().remove();
		$("#unqualifiedImgName").val();
	}
	var isChrome = false;
	if ( event.clipboardData || event.originalEvent ) {
		//not for ie11  某些chrome版本使用的是event.originalEvent
		var clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
		if ( clipboardData.items ) {
			// for chrome
			var  items = clipboardData.items,
			len = items.length,
			blob = null;
			isChrome = true;
			//items.length比较有意思，初步判断是根据mime类型来的，即有几种mime类型，长度就是几（待验证）
			//如果粘贴纯文本，那么len=1，如果粘贴网页图片，len=2, items[0].type = 'text/plain', items[1].type = 'image/*'
			//如果使用截图工具粘贴图片，len=1, items[0].type = 'image/png'
			//如果粘贴纯文本+HTML，len=2, items[0].type = 'text/plain', items[1].type = 'text/html'
			// console.log('len:' + len);
			// console.log(items[0]);
			// console.log(items[1]);
			// console.log( 'items[0] kind:', items[0].kind );
			// console.log( 'items[0] MIME type:', items[0].type );
			// console.log( 'items[1] kind:', items[1].kind );
			// console.log( 'items[1] MIME type:', items[1].type );
 
			//阻止默认行为即不让剪贴板内容在div中显示出来
			event.preventDefault();
 
			//在items里找粘贴的image,据上面分析,需要循环  
			for (var i = 0; i < len; i++) {
				if (items[i].type.indexOf("image") !== -1) {
					// console.log(items[i]);
					// console.log( typeof (items[i]));
 
					//getAsFile() 此方法只是living standard firefox ie11 并不支持        
					blob = items[i].getAsFile();
				}
			}
			if ( blob !== null ) {
				var reader = new FileReader();
				reader.onload = function (event) {
					// event.target.result 即为图片的Base64编码字符串
					var base64_str = event.target.result;
					//可以在这里写上传逻辑 直接将base64编码的字符串上传（可以尝试传入blob对象，看看后台程序能否解析）
					uploadImgFromPaste(base64_str, 'paste', isChrome);
				};
				reader.readAsDataURL(blob); 
			}
		} else {
			//for firefox
			setTimeout(function () {
				//设置setTimeout的原因是为了保证图片先插入到div里，然后去获取值
				var imgList = document.querySelectorAll('#tar_box img'),
				len = imgList.length,
				src_str = '',
				i;
				for ( i = 0; i < len; i ++ ) {
					if ( imgList[i].className !== 'my_img' ) {
						//如果是截图那么src_str就是base64 如果是复制的其他网页图片那么src_str就是此图片在别人服务器的地址
						src_str = imgList[i].src;
					}
		        }
		        uploadImgFromPaste(src_str, 'paste', isChrome);
			}, 1);
		}
	} else {
		//for ie11
		setTimeout(function () {
			var imgList = document.querySelectorAll('#tar_box img'),
			len = imgList.length,
			src_str = '',
			i;
			for ( i = 0; i < len; i ++ ) {
				if ( imgList[i].className !== 'my_img' ) {
					src_str = imgList[i].src;
				}
			}
			uploadImgFromPaste(src_str, 'paste', isChrome);
		}, 1);
	}
});

function uploadImgFromPaste (file, type, isChrome) {
	var formData = new FormData();
	formData.append('image', file);
	formData.append('submission-type', type);
 
	var xhr = new XMLHttpRequest();
	xhr.open("POST", "${contextPath}/security/inspPicUpload");
	xhr.onload = function () {
		if ( xhr.readyState === 4 ) {
			if ( xhr.status === 200 ) {
//				console.log(xhr.responseText);
				var data = JSON.parse( xhr.responseText );
				if(data.msg==1){
					var tarBox = document.getElementById('tar_box');
					if ( isChrome ) {
						var img = document.createElement('img');
						img.className = 'my_img';
						img.src = data.imgSrc;
						img.ondblclick = function(){//img双击事件  双击时在新的页面中显示图片
							window.open(this.src);
						};
						tarBox.appendChild(img);
						document.getElementById("unqualifiedImgName").value = data.imgName;
					} else {
						var imgList = document.querySelectorAll('#tar_box img'),
						len = imgList.length,
						i;
						for ( i = 0; i < len; i ++) {
							if ( imgList[i].className !== 'my_img' ) {
								imgList[i].className = 'my_img';
								imgList[i].src = data.imgSrc;
							}
						}
					}
				}else if(data.msg==2){
					alert("图片上传时出错,请联系系统维护人员!");
				}else if(data.msg==3){
					alert("图片上传时出错,浏览器兼容有问题,请联系系统维护人员!");
				}
				
	 
			} else {
				console.log( xhr.statusText );
			}
		}
	};
	xhr.onerror = function (e) {
		console.log( xhr.statusText );
	};
	xhr.send(formData);
}


	</script>
</body>
</html>
